"use client";
import { useEffect, useRef, useState } from "react";
import {
  createChart,
  IChartApi,
  UTCTimestamp,
  CandlestickData,
  HistogramData,
} from "lightweight-charts";

export default function Home() {
  const topRef = useRef<HTMLDivElement>(null);
  const bottomRef = useRef<HTMLDivElement>(null);
  const [stats, setStats] = useState("请按住 Shift 并拖动选择区间");

  useEffect(() => {
    if (!topRef.current || !bottomRef.current) return;

    // === 创建主图（K线） ===
    const topChart: IChartApi = createChart(topRef.current, {
      width: topRef.current.clientWidth,
      height: 400,
      layout: { background: { color: "#fff" }, textColor: "#333" },
      timeScale: { timeVisible: true, secondsVisible: false },
    });
    const candle = topChart.addCandlestickSeries();

    // === 创建副图（成交量） ===
    const bottomChart: IChartApi = createChart(bottomRef.current, {
      width: bottomRef.current.clientWidth,
      height: 150,
      layout: { background: { color: "#fff" }, textColor: "#333" },
      timeScale: { visible: false }, // 隐藏底部时间轴
    });
    const volume = bottomChart.addHistogramSeries({
      priceFormat: { type: "volume" },
      priceScaleId: "",
      scaleMargins: { top: 0.05, bottom: 0 },
    });

    // 同步滚动 & 缩放
    const topTS = topChart.timeScale();
    const bottomTS = bottomChart.timeScale();
    topTS.subscribeVisibleLogicalRangeChange(() => {
      const r = topTS.getVisibleLogicalRange();
      if (r) bottomTS.setVisibleLogicalRange(r);
    });

    let bars: (CandlestickData & { volume: number })[] = [];

    (async () => {
      const res = await fetch(
        "/api/kline?ts_code=SHSE.603986&bob_date=2025-08-21"
      );
      const raw = await res.json();

      bars = raw.map((d: any) => ({
        time: d.time as UTCTimestamp,
        open: +d.open,
        high: +d.high,
        low: +d.low,
        close: +d.close,
        volume: +d.volume,
      }));

      candle.setData(bars);
      volume.setData(
        bars.map(
          (b) =>
            ({
              time: b.time,
              value: b.volume,
              color: b.close >= b.open ? "#26a69a" : "#ef5350",
            } as HistogramData)
        )
      );
    })();

    // === 区间选择 ===
    let selecting = false;
    let startTime: UTCTimestamp | null = null;

    const clearRange = () => {
      startTime = null;
      selecting = false;
    };

    const onDown = (e: MouseEvent) => {
      if (!e.shiftKey) return;
      selecting = true;

      // ✅ 临时禁用图表交互
      topChart.applyOptions({
        handleScroll: { mouseWheel: false, pressedMouseMove: false },
        handleScale: { mouseWheel: false, pinch: false },
      });

      const x = e.clientX - topRef.current!.getBoundingClientRect().left;
      startTime = topTS.coordinateToTime(x) as UTCTimestamp | null;
    };

    const onUp = (e: MouseEvent) => {
      if (!selecting || !startTime) {
        clearRange();
        return;
      }
      selecting = false;

      // ✅ 恢复交互
      topChart.applyOptions({
        handleScroll: { mouseWheel: true, pressedMouseMove: true },
        handleScale: { mouseWheel: true, pinch: true },
      });

      const x = e.clientX - topRef.current!.getBoundingClientRect().left;
      const endTime = topTS.coordinateToTime(x) as UTCTimestamp | null;
      if (!endTime) {
        clearRange();
        return;
      }

      const from = Math.min(Number(startTime), Number(endTime)) as UTCTimestamp;
      const to = Math.max(Number(startTime), Number(endTime)) as UTCTimestamp;

      const sel = bars.filter((b) => b.time >= from && b.time <= to);
      if (sel.length < 2) {
        clearRange();
        setStats("区间数据不足");
        return;
      }

      const first = sel[0],
        last = sel[sel.length - 1];
      const pct = (((last.close - first.open) / first.open) * 100).toFixed(2);
      const avg = (
        sel.reduce((s, b) => s + b.close, 0) / sel.length
      ).toFixed(2);
      const vol = sel.reduce((s, b) => s + b.volume, 0);

      setStats(
        `区间: ${new Date(from * 1000).toLocaleTimeString()} ~ ${new Date(
          to * 1000
        ).toLocaleTimeString()} | 涨跌: ${pct}% | 均价: ${avg} | 总量: ${vol}`
      );

      clearRange();
    };

    topRef.current.addEventListener("mousedown", onDown);
    topRef.current.addEventListener("mouseup", onUp);

    return () => {
      topChart.remove();
      bottomChart.remove();
      topRef.current?.removeEventListener("mousedown", onDown);
      topRef.current?.removeEventListener("mouseup", onUp);
    };
  }, []);

  return (
    <div>
      <div ref={topRef} style={{ width: "100%", height: 400 }} />
      <div ref={bottomRef} style={{ width: "100%", height: 150 }} />
      <div style={{ padding: 8, fontSize: 14 }}>{stats}</div>
    </div>
  );
}
